﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using LybrixNursingCommon;
using LybrixNursingCRMDesktop.FrameWork;
namespace LybrixNursingCRMDesktop.Windows
{
    /// <summary>
    /// Interaction logic for AddSource.xaml
    /// </summary>
    public partial class AddSource : Window
    {
        private readonly LybrixNursingCommon.NursingDBContainer _entities;
        string payemtHeaderID;
        bool isNew = true;
        PaymentHeader currentPaymentHeader = null;
        Teek currentTeek = null;

        public AddSource( Teek _teek)
        {
            InitializeComponent();
            _entities = Repository.Entities;
            intializComboboxes();
            payemtHeaderID = GetUniqueID();
            HeaderLbl.Content = payemtHeaderID;
            currentTeek = _teek;
            isNew = true;
        }

        public AddSource(Teek _teek, PaymentHeader _paymentHeader)
        {
            InitializeComponent();
            _entities = Repository.Entities;
            intializComboboxes();
            payemtHeaderID = GetUniqueID();
            HeaderLbl.Content = payemtHeaderID;
            currentTeek = _teek;
            currentPaymentHeader = _paymentHeader;
            isNew = false;
            InitCusrrentNursingHome();
        }

        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            double _totalprice = 0;
            double teekPrice = 0;
            _totalprice  = calculatePayments();
            if (isNew)
            {
                PaymentHeader PaymentHeader = new PaymentHeader();
                PaymentHeader.Active = (bool)isActive.IsChecked;

                PaymentHeader.TotalAmount = totalAmount.Text;

                if (string.IsNullOrWhiteSpace(PaymentHeader.TotalAmount))
                {
                    MessageBox.Show("חובה למלא מחיר כולל של תיק", "שגיאה", MessageBoxButton.OK);
                    return;
                }
                if (!double.TryParse(PaymentHeader.TotalAmount, out teekPrice))
                {
                    MessageBox.Show("הכנס מספר בלבד", "שגיאה", MessageBoxButton.OK);
                    return;
                }


                PaymentHeader.Source = sourceName.Text;

                if (((ComboboxItem)(paymentHeaderStatus.SelectedItem)) != null)
                {
                    PaymentHeader.StatusId = ((ComboboxItem)(paymentHeaderStatus.SelectedItem)).Id;
                    PaymentHeader.Status_descr = ((ComboboxItem)(paymentHeaderStatus.SelectedItem)).Descr;
                }
                else
                {
                    PaymentHeader.StatusId = "-1";
                    PaymentHeader.Status_descr = string.Empty;
                }

                PaymentHeader.Teek = currentTeek;
                _entities.AddToPaymentHeaders(PaymentHeader);
                currentPaymentHeader = PaymentHeader;
                isNew = false;

            }

                double _payment = 0;
                TeekPayments teekPayment = new TeekPayments();
                if (txbpaymentAmount != null && dbpaymentDate.SelectedDate != null)
                {

          

                    
                    if (double.TryParse(txbpaymentAmount.Text, out _payment))
                        teekPayment.PaymentAmount = _payment;
                    else
                        MessageBox.Show("הכנס מספר בלבד", "שגיאה", MessageBoxButton.OK);


                    if ((_totalprice + _payment) > double.Parse(totalAmount.Text))
                    {
                        MessageBox.Show("הסכום הכללי של תשלומים גדול ממחיר תיק", "שגיאה", MessageBoxButton.OK);
                        return;
                    }


                    teekPayment.PaymentDate = (DateTime)dbpaymentDate.SelectedDate;

                    if (cmbMethods.SelectedItem != null)
                    {
                        teekPayment.PaymentMethodId = ((ComboboxItem)(cmbMethods.SelectedItem)).Id;
                        teekPayment.PaymentMethod = ((ComboboxItem)(cmbMethods.SelectedItem)).Descr;
                    }
                    else
                    {
                        teekPayment.PaymentMethod = "-1";
                        teekPayment.PaymentMethodId = string.Empty;
                    }

                    teekPayment.PaymentType = "A";
                    teekPayment.PaymentType_descr = "AA";
                    teekPayment.PaymentStatus_descr = "B";
                    teekPayment.PaymentStatusId = "B";
                    teekPayment.PaymentHeader = currentPaymentHeader;
                    _entities.AddToTeekPayments(teekPayment);
                }
                else
                {
                    MessageBox.Show("תשלום או תאריך תשלום חסרים בבקשה תמלא אותם", "אזהרה", MessageBoxButton.OK);
                    return;
                }
                 
        

            try
            {

                _entities.SaveChanges();
                MessageBox.Show("הרשומה נרשמה בהצלחה", "הודעה", MessageBoxButton.OK);
                ltteekPayments.ItemsSource = null;
                ltteekPayments.ItemsSource = currentPaymentHeader.TeekPayments;
                remainedAmount.Content = (calculatePayments()).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        private void InitCusrrentNursingHome()
        {
            double _totalAmount = 0;
            isActive.IsChecked = currentPaymentHeader.Active;
            totalAmount.Text = currentPaymentHeader.TotalAmount;
            sourceName.Text = currentPaymentHeader.Source;
            paymentHeaderStatus.SelectedItem = GetItem(paymentHeaderStatus, currentPaymentHeader.Status_descr);

            if (double.TryParse(currentPaymentHeader.TotalAmount, out _totalAmount))
            {

                remainedAmount.Content = (_totalAmount - calculatePayments()).ToString();
            }

            else
                remainedAmount.Content  = "לא ניתן לחשב";
            ltteekPayments.ItemsSource = currentPaymentHeader.TeekPayments;
        }




        private double calculatePayments()
        {
            double total = 0;
            List<TeekPayments> payments = null;

            if (currentPaymentHeader != null)
            {
                if (currentPaymentHeader.TeekPayments != null)
                {
                    payments = currentPaymentHeader.TeekPayments.ToList<TeekPayments>();

                    foreach (TeekPayments _payment in payments)
                    {
                        if (_payment.PaymentAmount == null)
                            continue;
                        else
                            total += _payment.PaymentAmount;
                    }
                    return total;
                }
                else
                    return 0;
            }

            else
                return 0;
        }


        private string GetUniqueID()
        {
            string tmpID = string.Empty;
            int lastvalue = 1;
            string headerID = string.Empty;
            formula _formula;

            var formulas = (from x in _entities.formulae where x.bo == "BPaymentHeaderFormula" select x);


            if (formulas.Count<formula>() == 0)
            {
                headerID = lastvalue.ToString("0000");
                _formula = new formula();
                _formula.bo = "BetAvotFormula";
                _formula.lastvalue = 1;
                _entities.AddToformulae(_formula);

            }
            else
            {
                lastvalue = (formulas.First<formula>()).lastvalue;
                _formula = formulas.First<formula>();
                headerID = (lastvalue + 1).ToString("0000");
                _formula.lastvalue = lastvalue + 1;
            }


            try
            {

                _entities.SaveChanges();
                return "SRC" + headerID;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }




        }

        private void intializComboboxes()
        {

            paymentHeaderStatus.ItemsSource = null;
            cmbMethods.ItemsSource = null;

            paymentHeaderStatus.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","נסגר"), 
                new ComboboxItem("2","נסגר בלי להשלים כל התשלמוים"), 
                new ComboboxItem("3","חסרים תשלומים"),
                new ComboboxItem("4","תשלומים מתעקבים")
            };
            paymentHeaderStatus.DisplayMemberPath = "Descr";
            paymentHeaderStatus.SelectedValuePath = "Id";


            cmbMethods.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","מזומן"), 
                new ComboboxItem("2","כרטיס אשראי"), 
                new ComboboxItem("3","שיק")
            };
            cmbMethods.DisplayMemberPath = "Descr";
            cmbMethods.SelectedValuePath = "Id";
           


        }
        private ComboboxItem GetItem(ComboBox combo, string value)
        {
            ComboboxItem _item = null;

            for (int i = 0; i < combo.Items.Count; ++i)
            {
                if (((ComboboxItem)(combo.Items[i])).Descr == value)
                {
                    _item = (ComboboxItem)combo.Items[i];
                    break;
                }

            }

            return _item;
        }

        private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {

        }

        private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {

        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

 
    }
}
